/*
 *  Copyright 2023 Alexey Andreev.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.teavm.classlib.java.util.concurrent.atomic;

import java.lang.reflect.Modifier;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;
import org.teavm.classlib.java.lang.TClass;
import org.teavm.classlib.java.lang.TIllegalAccessException;
import org.teavm.classlib.java.lang.TNoSuchFieldException;

public abstract class TAtomicReferenceFieldUpdater<T, V> {
    protected TAtomicReferenceFieldUpdater() {
    }

    public static <U, W> TAtomicReferenceFieldUpdater<U, W> newUpdater(TClass<U> tclass, TClass<W> vclass,
            String fieldName) {
        try {
            var field = tclass.getDeclaredField(fieldName);
            if (field.getType() != vclass) {
                throw new ClassCastException();
            }
            if (!Modifier.isVolatile(field.getModifiers()) || Modifier.isStatic(field.getModifiers())
                    || field.getType().isPrimitive()) {
                throw new IllegalArgumentException();
            } else {
                field.checkGetAccess();
                field.checkSetAccess();
                return new TReflectionBasedAtomicReferenceFieldUpdater<>(field);
            }
        } catch (TNoSuchFieldException | TIllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public abstract boolean compareAndSet(T obj, V expect, V update);

    public abstract boolean weakCompareAndSet(T obj, V expect, V update);

    public abstract void set(T obj, V newValue);

    public abstract void lazySet(T obj, V newValue);

    public abstract V get(T obj);

    public V getAndSet(T obj, V newValue) {
        while (true) {
            var currentValue = get(obj);
            if (compareAndSet(obj, currentValue, newValue)) {
                return currentValue;
            }
        }
    }

    public final V getAndUpdate(T obj, UnaryOperator<V> updateFunction) {
        while (true) {
            var currentValue = get(obj);
            var newValue = updateFunction.apply(currentValue);
            if (compareAndSet(obj, currentValue, newValue)) {
                return currentValue;
            }
        }
    }

    public final V updateAndGet(T obj, UnaryOperator<V> updateFunction) {
        while (true) {
            var currentValue = get(obj);
            var newValue = updateFunction.apply(currentValue);
            if (compareAndSet(obj, currentValue, newValue)) {
                return newValue;
            }
        }
    }

    public final V getAndAccumulate(T obj, V x, BinaryOperator<V> accumulatorFunction) {
        while (true) {
            var currentValue = get(obj);
            var newValue = accumulatorFunction.apply(currentValue, x);
            if (compareAndSet(obj, currentValue, newValue)) {
                return currentValue;
            }
        }
    }

    public final V accumulateAndGet(T obj, V x, BinaryOperator<V> accumulatorFunction) {
        while (true) {
            var currentValue = get(obj);
            var newValue = accumulatorFunction.apply(currentValue, x);
            if (compareAndSet(obj, currentValue, newValue)) {
                return newValue;
            }
        }
    }
}
